package com.study.service.Impl;

import com.study.enums.ResultCodeEnum;
import com.study.exception.MyException;
import com.study.mapper.UserMapper;
import com.study.pojo.dto.User;
import com.study.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> getUsers() {
        return userMapper.getUsers();
    }


    @Override
    public void register(User user) {
        // 以防万一 检测一下
        usernameExist(user.getUsername());
        user.setCode(String.valueOf(System.currentTimeMillis())); // 伪装一个code
        userMapper.register(user);
    }

    @Override
    public User login(String username, String password) {
        User login = userMapper.login(username, password);
        if (login == null) {
            throw new MyException("账号或密码错误");
        }
        return login;
    }

    @Override
    public void usernameExist(String username) {
        if (userMapper.usernameExist(username) > 0) {
            throw new MyException(ResultCodeEnum.USERNAME_ALREADY_EXISTS, "用户名已存在！");
        }
    }

    @Override
    public User queryUserByUsername(String username) {
        return userMapper.queryUserByUsername(username);
    }
}
